package com.anycl.design.structural.proxy.dynamicproxy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

@Slf4j
public class TicketerMain {

    public static void main(String[] args) {
        String name = "anycl";
        Ticketer buyer = new Ticketer(name);

        Enhancer enhancer = new Enhancer();
        // 设置代理对象的父类
        enhancer.setSuperclass(buyer.getClass());
        // 设置回调函数
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                Object object;
                // buyTicket操作前后进行通知操作，来模拟BuyerProxy
                if ("buyTicket".equals(method.getName())) {
                    before();
                    object = method.invoke(buyer, args);
                    after();
                } else {
                    object = method.invoke(buyer, objects);
                }
                return object;
            }
        });
        // 创建子类（代理对象）
        Ticketer ticketerProxy = (Ticketer) enhancer.create();
        ticketerProxy.login(name, "123456");
        ticketerProxy.buyTicket();

    }

    private static void before() {
        log.info("准备定时任务，开始刷票");
    }

    private static void after() {
        log.info("刷票成功，短信通知客户");
    }
}
